package com.tinem.platform.service.message.observable;

import com.alibaba.fastjson.JSON;
import com.tinem.platform.module.starter.jpa.entity.message.Message;
import com.tinem.platform.module.starter.jpa.repository.message.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className EMailListener
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-28 17:55
 */
@Service
@Order(200)
public class SaveListener implements ApplicationListener<MessageObservable> {

    @Autowired
    MessageRepository messageRepository;

    @Override
    public void onApplicationEvent(MessageObservable event) {
        Message message = new Message();
        message.setId(event.getId());
        message.setBody(event.getBody() instanceof String?((String)event.getBody()):(JSON.toJSONString(event.getBody())));
        message.setClientId(event.getClientId());
        message.setForm(event.getSource().getFrom());
        message.setSendTime(new Date());
        message.setParams(JSON.toJSONString(event.getSource().getParams()));
        message = messageRepository.saveAndFlush(message);
    }
}
